Create target array in the given order¶
Time: O(N^2); Space: O(1); easy
Given two arrays of integers nums and index. Your task is to create target array under the following rules:
Initially target array is empty. From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. Repeat the previous step until there are no elements to read in nums and index. Return the target array.
It is guaranteed that the insertion operations will be valid.
Example 1:
Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
Explanation:
nums index target
0 0 [0]
1 1 [0,1]
2 2 [0,1,2]<
3 2 [0,1,3,2]
4 1 [0,4,1,3,2]
Example 2:
Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]
Explanation:
nums index target
1 0 [1]
2 1 [1,2]
3 2 [1,2,3]
4 3 [1,2,3,4]
0 0 [0,1,2,3,4]
Example 3:
Input: nums = [1], index = [0]
Output: [1]
Notes:
1 <= len(nums), len(index) <= 100
len(nums) == len(index)
0 <= nums[i] <= 100
0 <= index[i] <= i
Hint:
Simulate the process and fill corresponding numbers in the designated spots.
[1]:
class Solution1(object):
def createTargetArray(self, nums, index):
"""
:type nums: List[int]
:type index: List[int]
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i):
if index[j] >= index[i]:
index[j] += 1
result = [0] * len(nums)
for i in range(len(nums)):
result[index[i]] = nums[i]
return result
[2]:
s = Solution1()
nums = [0,1,2,3,4]
index = [0,1,2,2,1]
assert s.createTargetArray(nums, index) == [0,4,1,3,2]
nums = [1,2,3,4,0]
index = [0,1,2,3,0]
assert s.createTargetArray(nums, index) == [0,1,2,3,4]
nums = [1]
index = [0]
assert s.createTargetArray(nums, index) == [1]
[3]:
class Solution2(object):
def createTargetArray(self, nums, index):
"""
:type nums: List[int]
:type index: List[int]
:rtype: List[int]
"""
result = []
for i, x in zip(index, nums):
result.insert(i, x)
return result
[4]:
s = Solution2()
nums = [0,1,2,3,4]
index = [0,1,2,2,1]
assert s.createTargetArray(nums, index) == [0,4,1,3,2]
nums = [1,2,3,4,0]
index = [0,1,2,3,0]
assert s.createTargetArray(nums, index) == [0,1,2,3,4]
nums = [1]
index = [0]
assert s.createTargetArray(nums, index) == [1]